<?php

include('pagina.php');
include('auth.php');
include('database.php');
include('core.php');

/* Verifica se logout */
if (isset($_GET['logout']))
{
/*  Avoid messing up with session of other apps,
    so, just unset our sessions */
//	session_destroy();
	unset($_SESSION[site_id]);
}

/* Verifica se login */
// Verifica as informacoes de post para validar o password
if (isset($_POST['username']) && isset($_POST['password']))
{
	// lower and scape username
	$username = mysql_real_escape_string(strtolower($_POST['username']));
	
	// lower, scape and calculate md5 hash for entered password
	$password = md5(mysql_real_escape_string(strtolower($_POST['password'])));

    /* First set an invalid login_id */
    $login_id = -1;

    /* Checks for admin login */
    if ($username == admin_username && $password == admin_password)
    {
        $login_id = 0;
        $login_name = admin_username;
        $login_permission = 4;
    }
    else
    {
        /* Checks for an employee login */
        $employee = query_fetch("SELECT * from employees WHERE " .
            "leaved IS NULL AND username='" . $username .
            "' AND password='" . $password . "' LIMIT 1");

        // Verifica se existe este usuario e senha
        if ($employee)
        {
            $login_id = $employee['id'];
            $login_name = $employee['username'];
            $login_permission = $employee['permission'];
        }
    }

    if ($login_id != -1)
    {
		// Creates session
        $_SESSION[site_id] = array(
            'id' => $login_id, 
            'permission' => $login_permission,
            'username' => $login_name);

		/* Verifica permissao */
		if ($_SESSION[site_id]['permission'] >= 3)
		{
			/* Atualiza incomes/expenses */
			$period_duedates = query_bd("SELECT * FROM period_duedates WHERE id > 1 AND next_duedate < NOW()");

			while ($period_duedate = mysql_fetch_array($period_duedates))
			{
				$next_duedate = strtotime($period_duedate['next_duedate']);

				while ($next_duedate < $_SERVER['REQUEST_TIME'])
				{
					switch ($period_duedate['period'])
					{
						case DAYLY:
							$next_duedate = next_day($next_duedate);
							break;
						case WEEKLY:
							$next_duedate = next_week($next_duedate);
							break;
						case FIFTEENTH:
							$next_duedate = next_fifteenth($next_duedate);
							break;
						case MONTHLY:
							$next_duedate = next_month($next_duedate);
							break;
						case YEARLY:
							$next_duedate = next_year($next_duedate);
							break;
					}
					// Cria duedate do period duedate
					query_bd("INSERT INTO duedates VALUES " .
					"(NULL, '{$period_duedate['name']}', '{$period_duedate['description']}', {$period_duedate['category']}, '" .
					date("Y-m-d", $next_duedate) .
					"' , {$period_duedate['value']}, FALSE, {$period_duedate['references_to']}, {$period_duedate['reference_id']}, " .
					($period_duedate['doc_number']? "'{$period_duedate['doc_number']}', " : "NULL, ") .
					($period_duedate['obs']? "'{$period_duedate['obs']}')" : "NULL)"));

					// Atualiza period duedate com o novo next duedate
					query_bd("UPDATE period_duedates SET next_duedate='" . date("Y-m-d", $next_duedate) .
					"' WHERE id={$period_duedate['id']}");
				}
				unset($period_duedate);
			}
			unset($period_duedates);
		}
		unset($employee);
        
		header("Location: " . (isset($_POST['page'])? $_POST['page'] : "employee.php?msg=Welcome to parksys"));
        exit;
	}
	else
	{
		$_GET['msg'] = "Your username or password is not valid.";
	}
}

/* Verifica se existe sessao */
else if (isset($_SESSION[site_id]))
{
	header("Location: " . (isset($_GET['page'])? $_GET['page'] : "employee.php") );
	exit;
}

/* Nao existe sessao... */
/* Inicia cabecalho da pagina */
pagina_inicio('ParkSys - login');
adicionar_css('login.css');
pagina_head();

?>
<script type="text/javascript" language="JavaScript">

function checkForm()
{

	if (document.getElementById('login').username.value.length == 0)
	{
		alert("The username field must not be empty.");
		return false;
	}
	else if (document.getElementById('login').password.value.length == 0)
	{
		alert("The password field must not be empty.");
		return false;
	}
	else
		return true;
}

</script>

<!-- Imprime formulario para login -->

<form id=login method=POST action=index.php onSubmit="return checkForm()" >
<img src="img/login.png" alt="Parksys login"><br>
<?php
 	if (isset($_GET['page']))
		echo "<input type='HIDDEN' value='" . $_GET['page'] . "' id=page name=page>";
?>
<label for=username>Username:</label><br><input type=TEXT value='' id=username name=username maxlength=20><br>
<label for=password>Password:</label><br><input type=PASSWORD value='' id=password name=password maxlength=20><br>
<input type=SUBMIT value='login' name='submit'>
</form>

<div id=forgot_password>
<a href='forgot_password.php'>Forgot your login/password?</a>
</div>

<?php

/* Finaliza pagina */
pagina_fim();
?>
